package com.es.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;

/**
 * @author 文雪峰
 * @date 2019/12/19 17:55
 * @description 将restClient交给sping管理
 **/
@Configuration
public class EsConfig {
    @Value("${spring.elasticsearch.jest.proxy.host}")
    private String host;


    private RestHighLevelClient restHighLevelClient;

    @Bean(destroyMethod="close")
    @Scope("singleton")
    public RestHighLevelClient createInstance() {
        try {
            if(StringUtils.isEmpty(host)){
                host = "127.0.0.1";
            }
            String[] hosts = host.split(",");
            HttpHost[] httpHosts = new HttpHost[hosts.length];
            for (int i = 0; i < httpHosts.length; i++) {
                String h = hosts[i];
                httpHosts[i] = new HttpHost(h.split(":")[0], Integer.parseInt(h.split(":")[1]), "http");
            }
            restHighLevelClient = new RestHighLevelClient(
                    RestClient.builder(httpHosts));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return restHighLevelClient;
    }
}
